//
//  FZEmoticonTool.swift
//  FZSina_Swift
//
//  Created by 李忠 on 7/30/16.
//  Copyright © 2016 FZLZ. All rights reserved.
//

import UIKit

let FZEmoticonMaxRow = 3
let FZEmoticonMaxCol = 7
let FZEmoticonMaxCount = FZEmoticonMaxRow * FZEmoticonMaxCol - 1

class FZEmoticonTool: NSObject {

    static let sharedTool: FZEmoticonTool = FZEmoticonTool()
    
    //得到文件的bundle
    lazy var emoticonBundle: NSBundle = {
        
        let filePath = NSBundle.mainBundle().pathForResource("Emoticons", ofType: "bundle")!
        return NSBundle(path: filePath)!
    }()
    //懒加载三维数组
    lazy var allEmoticons: [[[FZEmoticonModel]]] = {
        
        let defatults = self.getEmoticons("default")
        let emojis = self.getEmoticons("emoji")
        let lxhs = self.getEmoticons("lxh")
       
        let all: [[[FZEmoticonModel]]] = [
            self.getEmoticonGroup(defatults),
            self.getEmoticonGroup(emojis),
            self.getEmoticonGroup(lxhs)
        ]
        return all
    }()
    
    //MARK: 得到二位数组,一维数据做20等分切割，多出的也做一组
    func getEmoticonGroup(emoticons:[FZEmoticonModel]) -> [[FZEmoticonModel]] {
        
        let count = Int(ceil(CGFloat(emoticons.count) / CGFloat(FZEmoticonMaxCount)))
        
        var group: [[FZEmoticonModel]] = [[FZEmoticonModel]]()
        
        for i in 0..<count {

            //得到截取范围
            let location = i * FZEmoticonMaxCount
            var length = FZEmoticonMaxCount
            
            if FZEmoticonMaxCount + location > emoticons.count  {
                length = emoticons.count - location
            }
            
            let range = NSRange(location: location, length: length)
            let tempArray = (emoticons as NSArray).subarrayWithRange(range)
            group.append(tempArray as! [FZEmoticonModel])
        }
        return group
    }
    
    //MARK: 得到一维数组
    func getEmoticons(named: String) -> [FZEmoticonModel] {
        
        let filePath = emoticonBundle.pathForResource("\(named)/info", ofType: "plist")!
        
        
        
        let tempArray = NSArray(contentsOfFile: filePath)!
        var emoticons: [FZEmoticonModel] = [FZEmoticonModel]()
        
        for value in tempArray {
            let emoticon = FZEmoticonModel(dict: (value as! [String: AnyObject]))
            emoticon.path = "\(named)/\(emoticon.png ?? "")"
            emoticons.append(emoticon)
            
        }
        
        return emoticons
    }
    
}
